<template>
  <el-dialog title="选择素材" :visible.sync="dialogVisible" width="68%" :show-close="false" :center="true"
    :lock-scroll="true" custom-class="import-data-dlg" :close-on-press-escape="false" append-to-body>
    <div class="contain">
      <!-- 图片相关 -->
      <div class="contain-img-box mar-t-10 pad-l-20 pad-r-20 pad-b-20">
        <!-- 图片 -->
        <div class="tab-info">
          <span>图片</span>
        </div>
        <!-- 上传图片 -->
        <div class="mar-t-16">
          <el-button type="primary" :disabled="useSizeProgressBar >= 100" @click="upLoadDialogVisible = true">上传图片
          </el-button>
        </div>
        <!-- 图片信息区域 -->
        <div class="img-info flex mar-t-15">
          <!-- 左边分组信息 -->
          <div class="width-253 left-area pad-l-8 pad-t-15 pad-r-8">
            <!-- 分组搜索 -->
            <div>
              <el-input placeholder="请输入分组名称" v-model="groupQuery.groupName" @keyup.enter.native="handleSearchGroup"
                suffix-icon="el-icon-search"></el-input>
            </div>
            <!-- 分组名称信息 -->
            <div class="font-13 font-color-3 mar-t-10 group-list-box pad-b-30">
              <div>
                <div @click="changeGroup(index)" v-for="(item, index) of groupData" :key="index"
                  :class="groupIndex === index? 'gray':''" class="group-item height-38 flex pad-l-20 pad-r-10 pointer">
                  <span>{{item.groupName}}</span>
                  <div class="flex">
                    <span>{{item.materialCount}}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- 右边图片列表信息 -->
          <div class="flex-item pad-l-15 pad-r-20 right-area" v-loading="rightloading"
            element-loading-background="rgba(0, 0, 0, 0.8)">
            <div class="flex flex-between top-area height-63">
              <span class="font-18 font-color-3 font-w">{{selectGroupName}}</span>
              <div class="flex">
                <el-input v-model="materialQuery.materialName" placeholder="请输入内容"
                  @keyup.enter.native="handleSearchMaterial">
                </el-input>
                <div class="width-240 mar-l-15">
                  <el-button-group>
                    <el-button type="primary" @click="handleSearchMaterial">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                  </el-button-group>
                </div>
              </div>
            </div>
            <div class="flex height-62 operate">
              <div>
                <el-checkbox :disabled="this.isMultiple && this.multipleRemainNum >= 0" v-model="checkedAll" @change="changeCheckAll"
                  v-if="isMultiple">当页全选</el-checkbox>
                <span v-if="isMultiple">|</span>
                <span>已选{{selectImgList.length}}项</span>
              </div>
            </div>
            <!-- 图片列表 -->
            <div class="pad-r-15 mar-t-15" v-if="materialData.length > 0">
              <el-row :gutter="15">
                <el-col :span="3" v-for="(item,index) of materialData" :key="index" class="mar-b-10 pointer">
                  <div>
                    <div class="picture-box" @mouseenter="item.showMaterialSize = true"
                      @mouseleave="item.showMaterialSize = false">
                      <div class="flex">
                        <el-image ref="test-img" v-if="item.materialUrl" :style="{height: imgH}"
                          class="test width-per-100" :src="item.materialUrl" :preview-src-list="[item.materialUrl]">
                        </el-image>
                      </div>
                      <span
                        v-if="item.showMaterialSize && item.materialWidth && item.materialHeight">{{item.materialWidth}}*{{item.materialHeight}}</span>
                    </div>
                    <div>
                      <div class="inline-flex" @click.stop.prevent="selectImg(item)">
                        <el-checkbox v-model="item.isSelect" :disabled="!item.isSelect && item.disabled"></el-checkbox>
                        <span class="line-1 mar-l-4">{{item.materialName}}</span>
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div v-if="!materialData.length" class="font-color-9 flex flex-center" style="height: 70%;">
              暂无素材数据
            </div>
            <!-- 底部操作 -->
            <div class="right-footer-area flex flex-between pad-l-10 pad-r-10">
              <div class="flex">
                <div>
                  <el-checkbox :disabled="this.isMultiple && this.multipleRemainNum >= 0" v-model="checkedAll" @change="changeCheckAll"
                    v-if="isMultiple">当页全选</el-checkbox>
                  <span v-if="isMultiple">|</span>
                  <span>已选{{selectImgList.length}}项</span>
                </div>
              </div>
              <div>
                <div class="block">
                  <pagination :total="materialTotal" :page.sync="materialQuery.currentPage"
                    :limit.sync="materialQuery.size" @pagination="listMaterialList" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer pull-right">
        <el-button @click="closeMaterialSelect">取消</el-button>
        <el-button type="primary" @click="sureMaterialSelect">确定</el-button>
      </div>
      <multi-file-upload :dialogVisible="upLoadDialogVisible" action="/api/common/uploadFiles" :data="token"
        :onConfirm="addMultiFiles" :onCancel="hideMultiFileUpload" :isReturnFileWidthHeight="true"></multi-file-upload>
    </div>
  </el-dialog>
</template>

<script>
  import {
    getProjectMaterialGroupList,
    saveMaterialGroup,
    deleteMaterialGroup,
    pagingMaterialList,
    saveBatchMaterial,
    deleteMaterial,
    getMaterialUseTotalSize
  } from '@/api/material/handMaterial'
  import MultiFileUpload from '@/components/Upload/MultiFileUpload'
  import {
    getToken
  } from '@/utils/auth'
  export default {
    props: {
      dialogVisible: Boolean,
      onConfirm: Function,
      onCancel: Function,
      // 是否多选，默认：false
      isMultiple: Boolean,
      // 多选剩余数量：小于0为不限制
      multipleRemainNum: Number
    },
    data() {
      return {
        totalSize: 0, // 总大小
        useTotalSize: 0, // 已使用大小
        useSizeProgressBar: 0, // 已使用大小进度条
        token: '',
        materialType: 1, // 素材类型：1-图片，2-视频，默认：1-图片
        groupTotalMaterialNum: 0, // 分组下的所有素材数量
        groupQuery: {
          enterpriseId: this.getEnterpriseId(),
          groupName: '',
          isCustomGroup: true
        },
        visibleEditGroup: false,
        groupData: [], // 分组名称
        groupIndex: 0, // 当前分组
        selectImgList: [], // 选中的图片信息
        addGroupName: '', // 添加的分组名
        visible: false, // 添加分组输入框
        imgH: '',
        entity: {
          enterpriseId: this.getEnterpriseId(),
          groupName: '',
          groupId: ''
        },
        selectGroupName: '全部',
        materialTotal: 0,
        // 素材数据
        materialData: [],
        // 素材查询条件
        materialQuery: {
          enterpriseId: this.getEnterpriseId(),
          currentPage: 1,
          size: 20,
          materialType: this.materialType,
          materialName: '',
          materialGroupId: ''
        },
        upLoadDialogVisible: false,
        editMaterialVisible: false,
        editMaterialName: '',
        selectEditEntityMaterial: {},
        editGroupDialogVisible: false,
        editMaterialGroupId: '',
        rightloading: false
      }
    },
    components: {
      MultiFileUpload
    },
    computed: {
      // 是否全选
      checkedAll: {
        get() {
          if (this.materialData.length > 0) {
            return this.selectImgList.length === this.materialData.length
          }
          return false
        },
        set(value = false) {
          return value
        }
      }
    },
    directives: { // 使用局部注册指令的方式
      resize: { // 指令的名称
        bind(el, binding) { // el为绑定的元素，binding为绑定给指令的对象
          console.log(binding)
        }
      }
    },
    created() {
      if (this.isMultiple === undefined) {
        this.isMultiple = false
      }
      this.token = {
        accessToken: getToken()
      }
      this.listMaterialGroupList(true)
    },
    mounted() {
      const that = this
      window.onresize = () => {
        that.$nextTick(() => {
          if (this.$refs['test-img']) {
            that.imgH = document.querySelector('.el-col-3').clientWidth - 20 + 'px'
          }
        })
      }
    },
    updated() {
      const that = this
      this.$nextTick(() => {
        if (document.querySelector('.el-col-3')) {
          that.imgH = document.querySelector('.el-col-3').clientWidth - 20 + 'px'
        }
      })
    },
    methods: {
      listTotalSize() {
        var query = {
          enterpriseId: this.getEnterpriseId(),
          materialType: this.materialType
        }
        getMaterialUseTotalSize(query).then(response => {
          this.totalSize = response.data.totalSize
          this.useTotalSize = response.data.useTotalSize
          this.useSizeProgressBar = parseFloat(response.data.useSizeProgressBar)
        })
      },
      handleSearchGroup() {
        this.groupIndex = 0
        this.materialQuery.materialGroupId = ''
        this.listMaterialGroupList(true)
      },
      // 加载 素材分组数据
      // isLoadUseTotalSize：是否加载使用情况，默认是：true
      // isLoadMaterialData：是否加载素材数据，默认是：true
      listMaterialGroupList(isLoadUseTotalSize, isLoadMaterialData) {
        this.groupQuery.groupType = this.materialType
        if (isLoadUseTotalSize === undefined) {
          isLoadUseTotalSize = true
        }
        if (isLoadMaterialData === undefined) {
          isLoadMaterialData = true
        }
        if (isLoadMaterialData) {
          this.materialData = []
          this.materialTotal = 0
        }
        if (isLoadUseTotalSize) {
          // 获取使用情况
          this.listTotalSize()
        }
        getProjectMaterialGroupList(this.groupQuery).then(response => {
          this.groupData = response.data
          if (this.groupData && this.groupData.length > 0) {
            this.groupData.forEach((item, index) => {
              if (item.materialCount) {
                this.groupTotalMaterialNum = parseInt(this.groupTotalMaterialNum) + parseInt(item.materialCount)
              }
            })
          }
          if (isLoadMaterialData) {
            this.listMaterialList()
          }
        })
      },
      // 单击图片 显示图片遮罩
      selectImg(item) {
        if (!this.isMultiple) {
          this.selectImgList = []
          this.materialData.forEach((items) => {
            if (item.materialId !== items.materialId) {
              items.isSelect = false
            }
          })
        }
        item.isSelect = !item.isSelect
        if (item.isSelect) {
          if (this.isMultiple) {
            // 判断是否超过限制选择数量
            if (this.multipleRemainNum >= 0) {
              if (this.selectImgList.length + 1 >= this.multipleRemainNum) {
                this.materialData.forEach((subitem, index) => {
                  subitem.disabled = true
                })
              }
              if (this.multipleRemainNum === 0) {
                item.isSelect = false
                return
              } else {
                if (this.selectImgList.length >= this.multipleRemainNum) {
                  item.isSelect = false
                  return
                }
              }
            }
          }
          this.selectImgList.push(item)
        } else {
          this.materialData.forEach((subitem, index) => {
            subitem.disabled = false
          })
          this.selectImgList.forEach((subitem, index) => {
            if (subitem.materialId === item.materialId) {
              this.selectImgList.splice(index, 1)
            }
          })
        }
      },
      // 切换分组
      changeGroup(index) {
        this.rightloading = true
        this.resetData()
        this.groupIndex = index
        var data = this.groupData[index]
        if (data) {
          if (data.groupId > 0) {
            this.materialQuery.materialGroupId = data.groupId
          } else {
            this.materialQuery.materialGroupId = ''
          }
          this.selectGroupName = data.groupName
          this.listMaterialList()
        }
      },
      // 初始化数据
      resetData() {
        this.selectImgList = []
        this.materialQuery.currentPage = 1
      },
      // 批量分组
      batchGroup() {
        if (!this.selectImgList.length) {
          this.$message({
            message: '请先选择图片',
            type: 'warning'
          })
          return
        }
        this.editGroupDialogVisible = true
      },
      // 批量删除
      batchdeleteImg() {
        if (!this.selectImgList.length) {
          this.$message({
            message: '请先要删除的素材',
            type: 'warning'
          })
          return
        }
        const materialIds = []
        this.selectImgList.forEach((item, index) => {
          materialIds.push(item.materialId)
        })
        this.batchDeleteMaterialMethod(materialIds)
      },
      // 批量删除素材方法
      batchDeleteMaterialMethod(materialIds) {
        this.$confirm('确定要删除素材吗, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteMaterial(materialIds).then(response => {
            if (response.isError) return
            this.handleSearchMaterial()
            this.$message({
              message: response.msg,
              type: 'success'
            })
          })
        }).catch(() => {})
      },
      // 添加分组
      addGroup() {
        this.entity.groupId = ''
        this.entity.groupName = this.addGroupName
        this.saveGroup()
      },
      // 取消添加分组
      cancelAddGroup() {
        this.addGroupName = ''
        this.entity.groupName = ''
        this.entity.groupId = ''
        this.visible = false
      },
      openEditGroup() {
        if (this.groupIndex >= 0 && this.groupData && this.groupData.length > 0) {
          this.visibleEditGroup = true
          var data = this.groupData[this.groupIndex]
          this.entity.groupName = data.groupName
          this.entity.groupId = data.groupId
        }
      },
      // 取消编辑分组
      cancelEditGroup() {
        this.visibleEditGroup = false
        this.entity.groupName = ''
        this.entity.groupId = ''
      },
      saveGroup() {
        var that = this
        if (!that.entity.groupName) {
          that.$message({
            message: '请填写分组名称',
            type: 'error'
          })
          return
        }
        that.entity.groupType = that.materialType
        saveMaterialGroup(that.entity).then(response => {
          if (response.isError) return
          if (that.entity.groupId) {
            that.groupData[that.groupIndex].groupName = that.entity.groupName
          } else {
            that.listMaterialGroupList(false, false)
            if (that.groupData) {
              var groupId = that.groupData[that.groupIndex].groupId
              that.groupData.forEach((item, index) => {
                if (item.groupId === groupId) {
                  that.groupIndex = index
                  return
                }
              })
            }
          }
          that.cancelEditGroup()
          that.cancelAddGroup()
          that.$message({
            message: response.msg,
            type: 'success'
          })
        })
      },
      // 删除分组
      delGroup() {
        if (this.groupIndex >= 0 && this.groupIndex !== 1 && this.groupData && this.groupData.length > 0) {
          var data = this.groupData[this.groupIndex]
          this.$confirm('确定要删除【' + data.groupName + '】分组吗, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const groupIds = []
            groupIds.push(data.groupId)
            deleteMaterialGroup(groupIds).then(response => {
              if (response.isError) return
              this.handleSearchGroup()
              this.$message({
                message: response.msg,
                type: 'success'
              })
            })
          }).catch(() => {})
        }
      },
      // 单击全选框
      changeCheckAll(val) {
        if (val) {
          this.selectImgList = []
          this.materialData.forEach(item => {
            item.isSelect = true
            this.selectImgList.push(item)
          })
        } else {
          this.materialData.forEach(item => {
            item.isSelect = false
            this.selectImgList = []
          })
        }
      },
      // 获取素材列表
      listMaterialList() {
        this.selectImgList = []
        this.materialQuery.materialType = this.materialType
        pagingMaterialList(this.materialQuery).then(response => {
          this.materialTotal = response.data.total
          if (response.data.records) {
            response.data.records.forEach((item) => {
              item.showMaterialSize = false
              item.disabled = false
            })
          }
          this.materialData = response.data.records
          this.rightloading = false
        })
      },
      // 素材搜索
      handleSearchMaterial() {
        this.materialQuery.currentPage = 1
        this.listMaterialList()
      },
      // 素材搜索重置
      resetSearch() {
        this.materialQuery.materialName = ''
        this.materialQuery.currentPage = 1
        this.listMaterialList()
      },
      delMaterial(materialId) {
        if (materialId) {
          const materialIds = []
          materialIds.push(materialId)
          this.batchDeleteMaterialMethod(materialIds)
        }
      },
      addMultiFiles(imageUrls) {
        if (!imageUrls || !imageUrls.length) {
          return
        }
        const entityPush = []
        imageUrls.forEach(item => {
          if (!item.isError) {
            var entity = {
              enterpriseId: this.getEnterpriseId(),
              materialGroupId: this.materialQuery.materialGroupId,
              materialType: this.materialType
            }
            entity.materialName = item.fileName
            entity.materialUrl = item.imageUrl
            entity.materialSize = parseFloat(item.fileSize) / 1024
            entity.materialWidth = item.fileWidth
            entity.materialHeight = item.fileHeight
            entityPush.push(entity)
          }
        })

        saveBatchMaterial(entityPush).then(response => {
          if (response.isError) return
          this.$message({
            message: response.msg,
            type: 'success'
          })
          this.upLoadDialogVisible = false
          this.listMaterialGroupList(true)
        })
      },
      hideMultiFileUpload() {
        this.upLoadDialogVisible = false
      },
      openEditMaterial(item) {
        this.editMaterialName = item.materialName
        this.selectEditEntityMaterial = item
      },
      editMaterial(index) {
        if (!this.editMaterialName) {
          this.$message({
            message: '请填写素材名称',
            type: 'error'
          })
          return
        }
        if (this.editMaterialName === this.selectEditEntityMaterial.materialName) {
          this.$message({
            message: '素材名称没有修改!',
            type: 'error'
          })
          return
        }
        // 需要拷贝的对象
        const entityMaterial = JSON.parse(JSON.stringify(this.selectEditEntityMaterial))
        entityMaterial.materialName = this.editMaterialName
        const entityPush = []
        entityPush.push(entityMaterial)
        saveBatchMaterial(entityPush).then(response => {
          if (response.isError) return
          this.$message({
            message: response.msg,
            type: 'success'
          })
          this.cancelEditMaterial(index)
          this.selectEditEntityMaterial.materialName = this.editMaterialName
        })
      },
      cancelEditMaterial(index) {
        this.entityMaterial = {
          materialName: ''
        }
        this.closePopover(index)
      },
      closePopover(index) {
        for (const key in this.$refs) {
          if (key.indexOf('popover-') !== -1) {
            this.$refs[key][index].doClose()
          }
        }
      },
      // 批量修改分组
      handleCloseSelectMaterialGroup() {
        this.editGroupDialogVisible = false
        this.editMaterialGroupId = ''
      },
      // 确定批量修改素材分组
      handleSaveMaterialGroup() {
        var that = this
        if (!that.editMaterialGroupId) {
          that.$message({
            message: '请选择要修改分组!',
            type: 'error'
          })
          return
        }
        if (!that.selectImgList.length) {
          that.$message({
            message: '请先选择图片',
            type: 'warning'
          })
          return
        }

        that.selectImgList.forEach((item, index) => {
          item.materialGroupId = that.editMaterialGroupId
        })
        saveBatchMaterial(that.selectImgList).then(response => {
          if (response.isError) return
          this.$message({
            message: response.msg,
            type: 'success'
          })
          that.listMaterialGroupList(true)
          that.handleCloseSelectMaterialGroup()
        })
      },
      // 关闭选择素材
      closeMaterialSelect() {
        this.onCancel()
        this.selectImgList = []
        this.materialData.forEach((item) => {
          item.isSelect = false
          item.disabled = false
        })
      },
      // 确定选择素材
      sureMaterialSelect() {
        if (!this.selectImgList || this.selectImgList.length === 0) {
          this.$message({
            message: '请先选择素材',
            type: 'warning'
          })
          return
        }
        this.onConfirm(this.selectImgList)
        this.selectImgList = []
        this.materialData.forEach((item) => {
          item.isSelect = false
          item.disabled = false
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .contain {
    background: #F7F8FA;

    // 素材中心 图片空间
    .img-space-box {
      background: #fff;

      .title {
        color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
        background: #909399;
      }
    }

    //  图片相关
    .contain-img-box {
      background: #fff;

      .tab-info {
        height: 52px;
        border-bottom: 2px solid #EDEFF6;

        &>span {
          color: #409eff;
          display: flex;
          height: 100%;
          width: 85px;
          justify-content: center;
          align-items: center;
          border-bottom: 2px solid #409eff;
        }
      }

      // 图片信息区域
      .img-info {
        border: 2px solid #EDEFF6;

        // 左边
        .left-area {
          min-height: 600px;
          position: relative;

          .group-list-box::-webkit-scrollbar {
            width: 0 !important
          }

          .group-list-box {
            height: 500px;
            overflow-y: auto;
          }

          .group-item {
            justify-content: space-between;
            align-items: center;

            .group-btn {
              align-items: center;
              color: #409eff;
            }
          }

          .add-btn-box {
            width: 100%;
            position: absolute;
            bottom: 0;
            left: 0;
            box-shadow: 0px 0px 10px 2px #edeff6;
          }
        }

        .right-area {
          position: relative;
          border-left: 2px solid #EDEFF6;
          padding-bottom: 60px;

          .top-area {
            border-bottom: 1px solid #f5f5f5;
          }

          .operate {
            align-items: center;
            border-bottom: 1px solid #f5f5f5;
            ;
          }

          .right-footer-area {
            // padding: 10px;
            box-shadow: 0px 0px 10px 2px #edeff6;
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;

            &>div:nth-child(1) {
              align-items: center;
            }
          }

          .picture-box {
            position: relative;

            img {
              display: block;
            }

            &>span {
              position: absolute;
              bottom: 0;
              left: 0;
              width: 100%;
              background: rgba(0, 0, 0, 0.75);
              color: #fff;
              display: flex;
              justify-content: center;
              align-items: center;
              padding-top: 2px;
              padding-bottom: 2px;
            }
          }
        }
      }
    }
  }

  /deep/ .el-icon-circle-close {
    color: #fff;
  }

  .gray {
    background: #edeff6;
  }

  .blue {
    color: #409eff;
  }

  .pointer {
    cursor: pointer;
  }
</style>
